<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img" alt="" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editUserPhotoAPI } from '@/api'
export default {
  name: 'updatePhoto',
  data () {
    return {
      cropper: null
    }
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  methods: {
    onConfirm () {
      // console.log(this.cropper.getData()) //服务端方式
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updateUserPhoto(blob)
      })
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0// 持续展示
      })
      // console.log(blob) // 客户端方式
      // 错误的用法
      // 如果接口要求Content-Type是application/json
      // 则传递普通JavaScript对象
      // editUserPhotoAPI({
      //   photo: blob
      // })
      try {
        // 如果接口要求Content-Type是multipart/form-data
      // 则你必须传递FormData对象
        const formData = new FormData()
        // Pass the image file name as the third parameter if necessary.
        formData.append('photo', blob)
        const { data } = await editUserPhotoAPI(formData)
        console.log(data)
        // 关闭弹出层
        this.$emit('close')
        // 更新视图
        this.$emit('updataPhoto', data.data.photo)
        // 提示成功
        this.$toast.success('更新头像成功')
      } catch (error) {
        this.$toast.fail('更新头像失败')
      }
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 查看模式
      dragMode: 'move', // 拖动模式
      aspectRatio: 1, // 图片比例
      autoCropArea: 1, // 自动截取的区域
      cropBoxMovable: false, // 截取的区域是否可以移动
      cropBoxResizable: false, // 截图区域缩放
      background: false, // 背景
      movable: true // 画布是否可以移动
    //   aspectRatio: 16 / 9
    //   crop (event) {
    //     console.log(event.detail.x)
    //     console.log(event.detail.y)
    //     console.log(event.detail.width)
    //     console.log(event.detail.height)
    //     console.log(event.detail.rotate)
    //     console.log(event.detail.scaleX)
    //     console.log(event.detail.scaleY)
    //   }
    })
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  .img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
</style>
